package model;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "compras")
public class Compra implements Serializable {

    @Id
    @GeneratedValue (strategy=GenerationType.IDENTITY)
    @Column(name = "codigo")
    private int codigo;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "compra")
    private List<ItemCompra> itens = new ArrayList();

    public int getCodigo() {
        return codigo;
    }

    public void setCodigo(int codigo) {
        this.codigo = codigo;
    }

    public List<ItemCompra> getItens() {
        return itens;
    }

    public void setItens(List<ItemCompra> itens) {
        this.itens = itens;
    }

    public void addItem(ItemCompra item) {
        this.itens.add(item);
        item.setCompra(this);
    }

    public void removeItem(ItemCompra item) {
        this.itens.remove(item);
        item.setCompra(null);
    }

    public Double getValor() {
        Double retorno = new Double(0);
        for (ItemCompra itemCompra : itens) {
            retorno = retorno + itemCompra.getProduto().getPreco() * itemCompra.getQuantidade();
        }
        return retorno;
    }

}
